package com.cskaoyan.controller.wxaddress;

import com.cskaoyan.bean.MallAddress;
import com.cskaoyan.model.vo.BaseData;
import com.cskaoyan.model.vo.BaseRespVo;
import com.cskaoyan.service.wxaddress.WxAddressService;
import com.cskaoyan.utils.RegularUtil;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.Map;

/**
 * @Author: mjm
 * @Date: 2021/12/2
 * @Time: 11:03
 * @Description:
 */
@RestController
@RequestMapping("wx/address")
public class WxAddressController {
    @Autowired
    WxAddressService addressService;


    /**
     * @description: 获取地址列表
     * @param: 无参
     * @return:
     */
    @GetMapping("list")
    public BaseRespVo addressList() {

        Integer uid = (Integer) SecurityUtils.getSubject().getSession().getAttribute("uid");

        if (uid == null) return BaseRespVo.manual(501, "请登录", null);

        BaseData baseData = addressService.addressList(uid);

        return BaseRespVo.ok(baseData);
    }


    /**
     * @description: 根据id获取地址信息
     * @param: 无参
     * @return:
     */
    @GetMapping("detail")
    public BaseRespVo addressDetail(Integer id) {
        MallAddress mallAddress = addressService.addressDetail(id);
        return BaseRespVo.ok(mallAddress);

    }


    /**
     * @description: 保存地址信息
     * @param:
     * @return:
     */
    @PostMapping("save")
    public BaseRespVo addressSave(@RequestBody MallAddress mallAddress, HttpServletRequest request) {

        Integer uid = (Integer) request.getSession().getAttribute("uid");
        if (!RegularUtil.isMobile(mallAddress.getTel())) {
            return BaseRespVo.manual(401, "手机号不对", null);
        }
        mallAddress.setUserId(uid);
        int affectedRows = addressService.addressSave(mallAddress);
        if (affectedRows != 0) {
            return BaseRespVo.manual(0, "成功", 7);
        }
        return BaseRespVo.manual(401, "参数不对", null);

    }


    /**
     * @description: 删除地址信息
     * @param:
     * @return:
     */
    @PostMapping("delete")
    public BaseRespVo addressDelete(@RequestBody Map<String, Integer> map) {
        Integer id = map.get("id");
        int affectedRows = addressService.addressDelete(id);
        if (affectedRows != 0) {
            return BaseRespVo.manual(0, "成功", null);
        }
        return BaseRespVo.fail();
    }
}
